package com.xuetang9.t9.hotel.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName TokenLogin
 * @Description TODO
 * @Author qin
 * @Date 2020/3/1 10:03
 * @Version 1.0
 **/
public class TokenLogin {
    private static final String SECRET  = "ScorpioText";

    public static String createToken(String name,String rank){
        Date createDate = new Date();
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(Calendar.MINUTE,10);
        Date expiresDate = nowTime.getTime();
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("alg","HS256");
        map.put("type","JWT");
        String token = JWT.create()
                .withHeader(map)
                .withClaim("name",name)
                .withClaim("rank",rank)
                .withExpiresAt(expiresDate)//过期时间
                .withIssuedAt(createDate)
                .sign(Algorithm.HMAC256(SECRET));
        return token;
    }

    public static boolean verifyToken(String token){
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
        DecodedJWT jwt = null;
        try {
            jwt = verifier.verify(token);
            return true;
        } catch (Exception e) {
            return false;
//           throw new RuntimeException("验证不通过");
        }

//        return jwt.getClaims();
    }
}
